<template>
  <div>
    <h1>商户管理</h1>
    <div class="search-box">
      <input v-model="searchQuery" placeholder="搜索商户名称" />
      <input v-model="schoolId" placeholder="输入学校ID" type="number" required />
      <button @click="fetchMerchants">搜索</button>
    </div>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          
          <th>支付方式</th>
          <th>子商户号</th>
          <th>子商户名称</th>
          
          <th>服务商商户号</th>
          <th>备注</th>
          <th>创建时间</th>
          <th>操作时间</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="merchant in paginatedMerchants" :key="merchant.id">
          <td>{{ merchant.id }}</td>
          <td>{{ merchant.paymentMethod }}</td>
          <td>{{ merchant.subMchId }}</td>
          <td>{{ merchant.subMchName }}</td>
          <td>{{ merchant.mchId }}</td>
          <td>{{ merchant.remark }}</td>
          <td>{{ merchant.createTime }}</td>
          <td>{{ merchant.updateTime }}</td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { getMerchants } from '../api';

const merchants = ref([])
const schoolId = ref('')

// 移除watch(schoolId, fetchMerchants)

const fetchMerchants = async () => {
  if (!schoolId.value || isNaN(schoolId.value)) {
    alert('请输入有效的学校ID，必须为纯数字');
    return;
  }
  try {
    const response = await getMerchants(Number(schoolId.value));
    if (response) {
      merchants.value = response;
    }
  } catch (error) {
    console.error('获取商户数据失败:', error)
  }
}

const searchQuery = ref('')
const currentPage = ref(1)
const itemsPerPage = 10

const filteredMerchants = computed(() => {
  return merchants.value.filter(merchant => 
    merchant.subMchName.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

const paginatedMerchants = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage
  const end = start + itemsPerPage
  return filteredMerchants.value.slice(start, end)
})

const totalPages = computed(() => {
  return Math.ceil(filteredMerchants.value.length / itemsPerPage)
})

function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 8px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.search-box {
  margin-bottom: 16px;
}
</style>